package com.wl.studyjob.dbchange.zk;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Properties;

public class ZkClientDemo {

    ZkClient zkClient = null;
    @Before
    public void createClient(){
        zkClient = new ZkClient("linux121:2181,linux122:2181");
    }

    @Test
    public void createZknode(){
        zkClient.createPersistent("/wltest",true);
        System.out.println("zkclient create zknode");
    }

    @Test
    public void deleteZknode(){
        zkClient.deleteRecursive("/dbservers");
        System.out.println("zkclient delete zknode");
    }

    @Test
    public void getZknodeChange() throws InterruptedException {
        zkClient.subscribeChildChanges("/wltest", new IZkChildListener() {
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println(parentPath + "zknode"+ currentChilds +" changes");
            }
        });

        zkClient.createPersistent("/wltest");
        Thread.sleep(1000);

        zkClient.createPersistent("/wltest/test1");
        Thread.sleep(1000);

        zkClient.deleteRecursive("/wltest");
        Thread.sleep(1000);

        zkClient.createPersistent("/wltest/test1",true);
    }

    @Test
    public void getChangeData() throws InterruptedException {
        if(!zkClient.exists("/dbservers/db")){
            zkClient.createEphemeral("/wltest");
        }

        zkClient.subscribeDataChanges("/wltest", new IZkDataListener() {
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println(dataPath + "  data is change,new data  " + data);
            }

            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println(dataPath + "zknode is delete!!!");
            }
        });

        Object o = zkClient.readData("/wltest");
        System.out.println(o);

        zkClient.writeData("/wltest","aaa");
        Thread.sleep(1000);

        zkClient.delete("/wltest");

    }

    @After
    public void cloneClient(){
        zkClient.close();
    }

    @Test
    public void changeData(){
        Properties properties = new Properties();

        //initialSize=5
        properties.setProperty("initialSize","5");
        properties.setProperty("driverClassName","com.mysql.jdbc.Driver");
        properties.setProperty("url","jdbc:mysql://192.168.198.123:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=false");
        properties.setProperty("username","root");
        properties.setProperty("password","12345678");

        zkClient.writeData("/dbservers/db",properties);
        System.out.println(zkClient.readData("/dbservers/db"));
    }
}
